<template>
  <div class="full-height page-content mine-message  bg-white content padding-20">
    <div class="flex justify-between items-center tab-wrapper">
      <q-tabs
        v-model="tab"
        shrink stretch dense
        inline-label
        align="left"
        active-color="primary"
        indicator-color="primary"
      >
        <q-tab name="DLP_MSG_LABEL_ALL" label="全部" icon="iconfont iconqita-10"/>
        <q-tab name="DLP_MSG_LABEL_PRODUCTION" label="生产" icon="iconfont iconpingtaitubiao-51"/>
        <q-tab name="DLP_MSG_LABEL_DEVICE"  label="设备" icon="iconfont icontubiao2-86"/>
        <q-tab name="DLP_MSG_LABEL_CUTTER" label="刀具" icon="iconfont icontubiao5-09"/>
        <q-tab name="DLP_MSG_LABEL_REPAIR" label="维保" icon="iconfont iconpingtaitubiao-52"/>
        <q-tab name="DLP_MSG_LABEL_TOOLS" label="模具" icon="iconfont icontubiao5-08"/>
      </q-tabs>
      <q-icon name="iconfont iconshezhitubiao"
              style="font-size: 20px;"
              color="primary"
              class="toggle-icon cursor-pointer"
              @click="onSelectWorkShop">
        <q-tooltip>设置</q-tooltip>
      </q-icon>
    </div>
    <div class="flex margin-t-20 justify-between items-center">
      <div>
        <q-btn class="btn margin-r-10"
               outline
               color="primary"
               @click="batchRead"
               :disable="selected.length===0 || !haveNoRead"
               label="标记已读" />
        <q-btn class="btn margin-r-10"
               outline
               color="primary"
               @click="batchDeletion"
               :disable="selected.length===0"
               label="批量删除" />
      </div>
      <q-tabs
        class="tab-read"
        v-model="tabRead"
        shrink stretch dense
        inline-label
        align="left"
        active-color="primary"
        indicator-color="primary"
      >
        <q-tab name="2" label="全部"/>
        <q-tab name="1" label="已读"/>
        <q-tab name="0" label="未读"/>
      </q-tabs>
    </div>
    <q-table :data="tableData"
             :columns="columns"
             row-key="id"
             :loading="isTableLoading"
             :pagination.sync="pagination"
             :hide-bottom="!!tableData.length"
             selection="multiple"
             style="margin: 20px 0 0 0"
             class="myTable scroll"
             :selected.sync="selected"
             color="primary">
      <template v-slot:body-cell-title="{ row }">
        <q-td>
          <div class="flex items-center relative" style="flex-wrap: nowrap">
            <div class="unread" v-if="!row.read"></div>
            <img :src="`../../../../statics/img/home/${row.icon}.svg`" class="message-icon margin-r-10">
            {{row.businessName}}
          </div>
        </q-td>
      </template>
      <template v-slot:body-cell-content="{ row }">
        <q-td @click="showDetailContent(row)">
          {{row.content}}
        </q-td>
      </template>
      <template v-slot:body-cell-time="{ row }">
        <q-td>
          {{row.createTime | toNewDate}}
        </q-td>
      </template>
    </q-table>
    <yz-pagination v-model="pagination" @onSearch="getList"></yz-pagination>
    <msg-work-shop-dialog
      :show="isShowWorkShopDialog"
      @submit="onSubmitWorkShop"
      @close="isShowWorkShopDialog = false"/>
    <mes-detail :show="showDetail"
                :rowData="rowData"
                @close="showDetail=false"/>
  </div>
</template>
<script>
import MESLIST, { deleteMsgBySel, readMsgBatch } from 'src/boot/factory/mes-list.js'
import MES from './components/mes'
const { msgIconList, allMsgLabel } = new MES()
import MsgWorkShopDialog from './components/msg-work-shop-dialog'
import { mapGetters, mapActions, mapMutations } from 'vuex'
import MesDetail from './components/mes-detail'
import _ from 'lodash'
export default {
  name: 'mineMessage',
  components: {
    MsgWorkShopDialog,
    MesDetail
  },
  data () {
    return {
      tab: 'DLP_MSG_LABEL_ALL',
      tabRead: '2',
      selected: [], // 选中的产品id
      tableData: [], // 列表数据源
      // 表格分页配置
      pagination: {
        pageNum: 1, // 当前页码
        pageSize: 15, // 每页条数
        rowsNumber: 0 // 总条数
      },
      isTableLoading: false,
      columns: [
        { name: 'title', label: '标题', align: 'left', field: 'number' },
        { name: 'content', label: '内容', field: 'name', align: 'left' },
        { name: 'time', label: '时间', field: 'model', align: 'left' }
      ],
      isShowWorkShopDialog: false,
      showDetail: false,
      rowData: {}
    }
  },
  watch: {
    tab (val) {
      if (val) {
        this.pagination.pageNum = 1
        this.getList()
      }
    },
    tabRead (val) {
      if (val) {
        this.pagination.pageNum = 1
        this.getList()
      }
    },
    messageBodyData: {
      deep: true,
      immediate: true,
      handler (val) {
        if (val && val.length > 0) {
          const info = val.pop()
          this.onMessageArrived(info)
        }
      }
    }
  },
  computed: {
    ...mapGetters({
      'userInfo': 'userInfo',
      'messageBodyData': 'mes/messageBodyData'
    }),
    haveNoRead () {
      return this.selected.some(item => !item.read)
    }
  },
  created () {
    this.getList()
  },
  methods: {
    ...mapMutations({
      'SET_NUM': 'mes/SET_NUM'
    }),
    ...mapActions({
      'getReadNum': 'mes/getMsgRead' // 获取未读信息
    }),
    onMessageArrived (msg) {
      const responseData = msg.data
      if (this.tab === 'DLP_MSG_LABEL_ALL' || this.tab === responseData.label) {
        this.tableData.unshift({
          content: responseData.msgText.replaceAll('\n', '；'),
          cloneContent: responseData.msgText,
          businessName: responseData.businessDesc,
          id: responseData.id,
          label: responseData.label,
          read: false,
          createTime: new Date(),
          icon: msgIconList.get(responseData.label)?.icon
        })
      }
    },
    setDetailContent (row) {
      return {
        ...row,
        content: row.cloneContent
      }
    },
    // 获取所有的消息
    getList () {
      const params = {
        current: this.pagination.pageNum,
        label: this.tab === 'DLP_MSG_LABEL_ALL' ? allMsgLabel : this.tab,
        size: this.pagination.pageSize,
        read: this.tabRead
      }
      this.isTableLoading = true
      MESLIST.getMsgList(params).then(res => {
        const data = res.data
        this.tableData = data.records
        this.tableData.forEach(item => {
          item.icon = msgIconList.get(item.label)?.icon
          item.cloneContent = _.cloneDeep(item.content)
          item.content = item.content.replaceAll('\n', '；')
        })
        this.pagination.rowsNumber = data.total
      }).finally(() => {
        this.isTableLoading = false
      })
    },
    // 批量删除
    batchDeletion () {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>确认删除所选消息？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      })
        .onOk(() => {
          const userId = this.userInfo.user_id
          this.isTableLoading = true
          deleteMsgBySel(userId, this.selected).then(() => {
            this.selected = []
            this.getList()
            this.getReadNum(userId)
          }).catch(() => {
            this.isTableLoading = false
          })
        })
    },
    // 标记已读
    batchRead () {
      const msgIds = this.selected.map(item => item.id)
      this.isTableLoading = true
      readMsgBatch(msgIds).then(res => {
        this.selected = []
        this.getList()
        const userId = this.userInfo.user_id
        this.getReadNum(userId)
      }).catch(() => {
        this.isTableLoading = false
      })
    },
    // 设置弹窗
    onSelectWorkShop () {
      this.isShowWorkShopDialog = true
    },
    // 保存设置
    onSubmitWorkShop () {
      this.isShowWorkShopDialog = false
      const userId = this.userInfo.user_id
      this.getReadNum(userId)
      this.getList()
    },
    showDetailContent (row) {
      this.showDetail = true
      this.rowData = this.setDetailContent(row)
    }
  }
}
</script>
<style lang="scss" scoped>
.tab-wrapper{
  border-bottom: 1px solid #D3D3D3;
}
.btn{
  padding: 0;
  line-height: 1;
  height: 32px;
  min-width: 96px;
  min-height: 32px;
}
.tab-read /deep/.q-tab{
  margin: 0!important;
  min-height: 32px!important;
  height: 32px;
  border-right: 1px solid #d3d3d3;
  color: #999999!important;
}
.tab-read /deep/.q-tabs__content{
  border: 1px solid #d3d3d3;
  border-right: none;
  border-radius: 6px;
  overflow: hidden;
}
.tab-read /deep/.q-tab--active{
  background: #5F77FD;
  color: #ffffff!important;
}
.message-icon{
  width: 28px;
  height: 28px
}
.unread{
  width: 10px;
  height: 10px;
  background: #E43434;
  border-radius: 50%;
  position: absolute;
  left: -5px
}
</style>
